package com.ding.easycontroller.controller;

import com.ding.easycontroller.bean.ConsoleWork;
import com.ding.easycontroller.exception.CheckException;
import com.ding.easycontroller.exception.ScriptRuntimeException;
import com.ding.easycontroller.model.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.script.ScriptException;

@RestControllerAdvice
public class Advice {

    @Autowired
    private ConsoleWork consoleWork;

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ScriptRuntimeException.class)
    public void error(ScriptRuntimeException e) {
        consoleWork.log(e.getMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(RuntimeException.class)
    public R error(RuntimeException e) {
        R r = new R();
        r.setStatus(400);
        r.setMsg(e.getMessage());
        return r;
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(CheckException.class)
    public R checkError(CheckException e) {
        R r = new R();
        r.setStatus(500);
        r.setMsg(e.getMessage());
        return r;
    }

}
